<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
    <style>
      .list {
        width: 200px;
        height: 300px;
        background-color: yellow;
        overflow: auto;
      }
      .news {
        height: 30px;
      }
    </style>
  </head>
  <body>
    <!-- 准备好一个容器 -->
    <div id="test"></div>

    <!-- 引入react 核心库 -->
    <script
      type="text/javascript"
      src="../../react-js/react.development.js"
    ></script>
    <!-- 引入react-dom 用于支持react操作dom -->
    <script
      type="text/javascript"
      src="../../react-js/react-dom.development.js"
    ></script>
    <!-- 引入babel 用于jsx转为js -->
    <script type="text/javascript" src="../../react-js/babel.min.js"></script>

    <script type="text/babel">
      class NewList extends React.Component {
        state = { newList: [] };

        componentDidMount() {
          setInterval(() => {
            // 获取原状态
            const { newList } = this.state;
            // 模拟一条新闻
            const news = '新闻' + (newList.length + 1);
            // 更新状态
            this.setState({ newList: [news, ...newList] });
          }, 1000);
        }

        getSnapshotBeforeUpdate() {
          return this.refs.list.scrollHeight;
        }
        componentDidUpdate(preProps, preState, height) {
          this.refs.list.scrollTop += this.refs.list.scrollHeight - height;
        }
        render() {
          return (
            <div className='list' ref='list'>
              {this.state.newList.map((n, index) => {
                return (
                  <div key={index} className='news'>
                    {n}
                  </div>
                );
              })}
            </div>
          );
        }
      }
      ReactDOM.render(<NewList />, document.getElementById('test'));
    </script>
  </body>
</html>
